//
//  ZCSearchVC.m
//  zctx
//
//  Created by ZhengDarren on 15/9/28.
//  Copyright © 2015年 sanliang. All rights reserved.
//

#import "ZCSearchVC.h"

#import "ZCSeeResultVC.h"
#import "ZCRaiseVC.h"
#import "ZCSearchModel.h"

#import "ZCsearchHistoryDataBase.h"
#import "DZWebViewController.h"


#import "ZCSearchQualifiedCell.h"
#import "ZCSearchInvolvedCell.h"
#import "ZCSearchSamplingCell.h"
#import "ZCSearchCell.h"
#import "ZCSearchQualifiedOKCell.h"

#import "ZCSamplingDetailVC.h"
#import "ZCInvolvedDetailsVC.h"
#import "ZCProjectdetailsVC.h"


@interface ZCSearchVC ()<UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate>

@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) UIBarButtonItem *searchButton;
@property (nonatomic, strong) UITableView *tableView;


//data
@property (nonatomic, assign) NSInteger offset; //页数
@property (nonatomic, assign) NSInteger Intdata; //1表示有搜索结果 ，2表示推荐
@property (nonatomic, strong) NSMutableArray *arrResult; //搜索结果数组
@property (nonatomic, strong) NSMutableArray *dataArray; //本地搜索记录

@property BOOL issearch;
@end

@implementation ZCSearchVC


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"ZCSearchVC"];
    [MTA trackPageViewBegin:@"ZCSearchVC"];
    self.tabBarController.hidesBottomBarWhenPushed = YES;
    
    self.dataArray = [[ZCsearchHistoryDataBase shareDataBase]readLocalArray];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"ZCSearchVC"];
    [MTA trackPageViewEnd:@"ZCSearchVC"];
}

-(void)updateRequest{
    if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus >0) {
        self.bannerView.hidden = YES;
    }
    [self requestMainList];
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    //AF 开启监听网络状态
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [self initnavegation];
    self.offset = 0;
    self.Intdata = 1;
    self.issearch = YES;
    self.arrResult = [NSMutableArray array];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#ebeded"];
    NSLog(@"index = %@",theAppdelegate.tabbarIndex);
    self.searchBar.text = self.searchStr;
    
    [self initTableView];
    [self requestMainList];
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    [self.tableView registerNib:[UINib nibWithNibName:@"ZCSearchQualifiedOKCell" bundle:nil] forCellReuseIdentifier:@"qualifiedOKcell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ZCSearchQualifiedCell" bundle:nil] forCellReuseIdentifier:@"SearchQualified"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ZCSearchInvolvedCell" bundle:nil] forCellReuseIdentifier:@"SearchInvolved"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ZCSearchSamplingCell" bundle:nil] forCellReuseIdentifier:@"SearchSampling"];
    self.tableView.mj_footer = [MJDIYFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
}

#pragma mark 导航栏
-(void)initnavegation{
    
    UIButton * leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 19, 36);
    [leftButton setImage:[UIImage imageNamed:@"navigation_back"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(backButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * barButtonItem_leftNavBar = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    
    UIView * spaceView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,5, 32)];
    UIBarButtonItem * barButtonItem_spaceView = [[UIBarButtonItem alloc] initWithCustomView:spaceView];
    self.navigationItem.leftBarButtonItems = @[barButtonItem_leftNavBar,barButtonItem_spaceView];
    
    self.navigationItem.rightBarButtonItems = @[self.searchButton,barButtonItem_spaceView];
    
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-140, 30)];//allocate titleView
    UIColor *color =  self.navigationController.navigationBar.barTintColor;
    [titleView setBackgroundColor:color];
    _searchBar = [[UISearchBar alloc] init];
    _searchBar.delegate = self;
    _searchBar.frame = CGRectMake(0, 0, SCREEN_WIDTH-140, 30);
    _searchBar.backgroundColor = color;
    _searchBar.layer.cornerRadius = 15;
    _searchBar.layer.masksToBounds = YES;
    _searchBar.clearsContextBeforeDrawing = YES;
    [_searchBar.layer setBorderWidth:8];
    [_searchBar.layer setBorderColor:[UIColor whiteColor].CGColor];  //设置边框为白色
    _searchBar.placeholder = @"搜索产品 查看食品检测报告";
    [titleView addSubview:_searchBar];
    //Set to titleView
    [self.navigationItem.titleView sizeToFit];
    self.navigationItem.titleView = titleView;
}

-(void)backButtonPressed{
    [self.searchBar resignFirstResponder];
    if ([self.isbao isEqualToString:@"1"]) {
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        [self cancelAction];
    }
}

#pragma mark - 取消操作
- (void)cancelAction{
    
    CATransition *animation = [CATransition animation];
    animation.duration = 0.5;
    animation.timingFunction = UIViewAnimationCurveEaseInOut;
    animation.type = @"pageUnCurl";
    animation.type = kCATransitionFade;
    //    animation.subtype = kCATransitionFromBottom;
    [self.view.window.layer addAnimation:animation forKey:nil];
    
    [self dismissViewControllerAnimated:NO completion:^{
        
    }];
}



-(void)initTableView{
    _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.tableFooterView = [[UIView alloc] init];
    _tableView.sectionFooterHeight = 0.0001;
    _tableView.separatorColor = RGB(236, 237, 238);
    _tableView.backgroundColor = [UIColor colorWithHexString:@"#fafcfb"];
    [self.view addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(0,0,0,0));
    }];
}


#pragma mark 加载更多
-(void)loadMoreData{
    //上拉加载
    _offset = _offset+1;
    [self requestMainList];
}
#pragma mark - request 搜索请求
- (void)requestMainList {
    NSString *searchStr = @"";
    NSString *searchText = [NSString stringWithFormat:@"%@",self.searchBar.text];
    NSMutableString *ms = [[NSMutableString alloc] initWithString:searchText];
    if ([searchText length]) {
        if (CFStringTransform((__bridge CFMutableStringRef)ms, 0, kCFStringTransformMandarinLatin, NO)) {
            NSLog(@"pinyin: %@", ms);
        }
        if (CFStringTransform((__bridge CFMutableStringRef)ms, 0, kCFStringTransformStripDiacritics, NO)) {
            NSLog(@"pinyin: %@", ms);
        }
    }
    NSString *Pinyin = [ms stringByReplacingOccurrencesOfString:@" " withString:@","];
    if (Pinyin) {
        searchStr = Pinyin;
    }
    if (_offset ==0) {
        [GMDCircleLoader setOnView:self.view withTitle:@"努力加载中..." animated:YES];
    }
    if (self.isbao && [self.isbao isEqualToString:@"1"]) { //曝光台
        [NetworkManager requestProductGetUnsafeInfoByKeywordsPageWithMid:UserModel.mid keywords:searchText keywords_py:searchStr pagecount:[NSString stringWithFormat:@"%ld",(long)_offset] success:^(NSDictionary *dictResponse) {
            [self.tableView.mj_footer endRefreshing];
            [GMDCircleLoader hideFromView:self.view animated:YES];
            [self requestProductGetInfosuccess:dictResponse];
        } failure:^(NSError *error) {
            [GMDCircleLoader hideFromView:self.view animated:YES];
            if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == 0) {
                self.bannerView.hidden = NO;
            }
        }];
    }else{
        [NetworkManager requestProductGetInfoByKeywordsWithMid:UserModel.mid keywords:searchText keywords_py:Pinyin pagecount:[NSString stringWithFormat:@"%ld",(long)_offset] success:^(NSDictionary *dictResponse) {
            [self.tableView.mj_footer endRefreshing];
            [GMDCircleLoader hideFromView:self.view animated:YES];
            [self requestProductGetInfosuccess:dictResponse];
        } failure:^(NSError *error) {
            [GMDCircleLoader hideFromView:self.view animated:YES];
            if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == 0) {
                self.bannerView.hidden = NO;
            }
        }];
    }
}

#pragma mark 数据请求成功后调用
-(void)requestProductGetInfosuccess:(NSDictionary *)dictResponse{
    
    if([[dictResponse allKeys] containsObject:@"more_data"])
    {
        NSLog(@"sdfasdf");
        NSObject *objec_more = [dictResponse objectForKey:@"more_data"];
        if (_offset == 0) {
            self.issearch = NO;
            self.Intdata = 2;
        }else{
            self.issearch = YES;
        }
        if (self.Intdata == 1) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }else{
            if ([objec_more isKindOfClass:[NSDictionary class]]){
                NSDictionary *moreDict = (NSDictionary *)objec_more;
                if ([[moreDict objectForKey:@"recommend_data"] isKindOfClass:[NSArray class]]) {
                    NSArray *array =(NSArray *)[moreDict objectForKey:@"recommend_data"];
                    if (array !=nil && ![array isKindOfClass:[NSNull class]] && array.count !=0){
                        [self.arrResult addObjectsFromArray:array];
                        [self.tableView reloadData];
                    }else{
                        [self.tableView.mj_footer endRefreshingWithNoMoreData];
                    }
                }
            }
        }
    }
    else
    {
        NSLog(@"no____sdfasdf");
        NSObject *object = [dictResponse objectForKey:@"content"] ;
        self.issearch = YES;
        self.Intdata = 1;
        if ([object isKindOfClass:[NSArray class]]){
            NSArray *array =(NSArray *)object;
            if (array !=nil && ![array isKindOfClass:[NSNull class]] && array.count !=0){
                [self.arrResult addObjectsFromArray:array];
                [self.tableView reloadData];
            }
        }
    }
}

#pragma mark - 搜索 click

- (void)searchButtonClick {
    [_searchBar resignFirstResponder];
     [self.arrResult removeAllObjects];
    _offset = 0;
    [self requestMainList];
    [self.tableView setContentOffset:CGPointMake(0, -64) animated:NO];
    if (![NSString isNull:self.searchBar.text]) {
        [self addHotHistoryWithString:self.searchBar.text];
    }
}

#pragma mark - UISearchBar Delegate Methods

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [_searchBar resignFirstResponder];
     [self.arrResult removeAllObjects];
    _offset = 0;
    [self requestMainList];
    
    [self.tableView setContentOffset:CGPointMake(0, -64) animated:NO];
    
    if (![NSString isNull:self.searchBar.text]) {
        [self addHotHistoryWithString:self.searchBar.text];
    }
}

-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
   
}

#pragma mark - UITableView DataSource & Delegate Methodsd

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.arrResult.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZCSearchModel *model;
    if (self.arrResult.count>0) {
        model = [ZCSearchModel modelObjectWithDictionary:self.arrResult[indexPath.row]];
    }
       if (model.isurl==1 ||model.result==1||model.result==2) {
        if (model.qualified == 1 || model.result ==1) {
             static NSString *cellIndentity = @"qualifiedOKcell";
             ZCSearchQualifiedOKCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentity];
             if (!cell) {
                 cell = [[ZCSearchQualifiedOKCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentity];
             }
            cell.model = model;
             return cell;
        }else{
            static NSString *cellIndentity = @"SearchQualified";
            ZCSearchQualifiedCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentity];
            if (!cell) {
                cell = [[ZCSearchQualifiedCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentity];
            }
            cell.searchModel = model;
            return cell;
        }
    }else{
        
        if (model.state==1) {
            static NSString *cellid =@"SearchInvolved";
            ZCSearchInvolvedCell *cell = [tableView dequeueReusableCellWithIdentifier:cellid];
            if (cell == nil) {
                cell = [[ZCSearchInvolvedCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid];
            }
            cell.SearchModel = model;
            return cell;
        }
        else
        {// 0 审核中  2 抽样中 3完成 4 异常
            static NSString *cellid =@"SearchSampling";
            ZCSearchSamplingCell *cell = [tableView dequeueReusableCellWithIdentifier:cellid];
            if (cell == nil) {
                cell = [[ZCSearchSamplingCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid];
            }
            cell.samplingModel = model;
            return cell;
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 92;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (self.issearch == NO) {
        return 80;
    }else{
        return 0.0001;
    }
    return 0.0001;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headView = [[UIView alloc]init];
    if (self.issearch ==NO) {
        headView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 60);
        headView.backgroundColor = RGB(254, 248, 227);
        UIImageView *imgView = [[UIImageView alloc]init];
        [headView addSubview:imgView];
        [imgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(headView.centerY);
            make.height.mas_equalTo(@(20));
            make.left.mas_equalTo(@(20));
            make.width.mas_equalTo(@(20));
        }];
        imgView.image = [UIImage imageNamed:@"search_help"];
        
        UILabel *PromptLable = [[UILabel alloc]init];
        PromptLable.numberOfLines = 0;
        PromptLable.lineBreakMode = NSLineBreakByCharWrapping;
        [headView addSubview:PromptLable];
        [PromptLable mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(headView.centerY);
            make.height.equalTo(headView.height);
            make.left.equalTo(imgView.right).with.offset(5);
            make.right.equalTo(headView.right).with.offset(-20);
        }];
        PromptLable.text = @"暂无相关内容\n为您推荐以下最新检测报告";
        PromptLable.textColor = [UIColor colorWithHexString:@"#b2b2b2"];
        PromptLable.font = [UIFont systemFontOfSize:15];
        return headView;
    }else{
        return headView;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.0001;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [self.searchBar resignFirstResponder];
    ZCSearchModel *model;

    if (self.arrResult.count>0) {
        model = [ZCSearchModel modelObjectWithDictionary:self.arrResult[indexPath.row]];
    }
    if (model.isurl ==1) {
        DZWebViewController *vc = [[DZWebViewController alloc] init];
        vc.hidesBottomBarWhenPushed = YES;
        vc.strURL = model.url;
        vc.title = @"检测项目详情";
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        if (model.result !=0) { //合格、不合格
            ZCInvolvedDetailsVC *detailVC = [[ZCInvolvedDetailsVC alloc]init];
            detailVC.pid = model.internalZCSearchModelIdentifier;
            detailVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:detailVC animated:YES];

        }else{
            if (model.state == 2) { //抽样中
                ZCInvolvedDetailsVC *detailVC = [[ZCInvolvedDetailsVC alloc]init];
                detailVC.pid = model.internalZCSearchModelIdentifier;
                detailVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:detailVC animated:YES];
            }else{
                ZCInvolvedDetailsVC *detailVC = [[ZCInvolvedDetailsVC alloc]init];
                detailVC.pid = model.internalZCSearchModelIdentifier;
                detailVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:detailVC animated:YES];
            }
        }
    }
    [self performSelector:@selector(unselectCell:) withObject:nil afterDelay:0.3];
}

-(void)unselectCell:(id)sender{
    [self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
}

//添加一条历史记录
- (void)addHotHistoryWithString:(NSString *)string{
    
    //先改变tableview的数据源
    if ([self.dataArray containsObject:string]) {
        [self.dataArray removeObject:string];
    }
    [self.dataArray insertObject:string atIndex:0];
    
    //存储新的数据源到本地，以保证下次打开程序有之前搜索的记录
    [[ZCsearchHistoryDataBase shareDataBase]writeLocalWithDataArray:self.dataArray];
}

#pragma mark - instance
- (UIBarButtonItem *)searchButton {
    if (!_searchButton) {
        _searchButton = [[UIBarButtonItem alloc] initWithTitle:@"搜索" style:UIBarButtonItemStylePlain target:self action:@selector(searchButtonClick)];
    }
    return _searchButton;
}

-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc]init];
    }
    return _dataArray;
}

@end
